<template>
    <div>
        <div @click="play">
            播放·
        </div>
        <video ref="remoteVideo" crossorigin="anonymous" webkit-playsinline playsinline x5-playsinline
               x-webkit-airplay="allow" autoplay controls
               style="width: 100%; height: 440px; background: black;"></video>
    </div>
</template>
<script>
import {axiosInstance} from "@/static/common";
import md5 from 'js-md5'
export default {
    name: 'webrtc',
    methods: {
        async play() {
			
			
			
			
			var that = this
			const mySecret = "f6fdffe48c908deb0f4c3bd36c032e72"
			var params = {}
			params.t = (new Date().getTime() / 1000).toFixed(0)
			let str = "";
			    let keys = Object.keys(params);
			    keys.push("secret");
			    keys = keys.sort(); // 对参数 key 进行排序
			    keys.forEach((key) => {
			        if (key == "token") {
			            return;
			        }
			        if (str != "") {
			            str += "&";
			        }
			        if (key == "secret") {
			            str += `${key}=${mySecret}`;
			        } else {
			            str += `${key}=${params[key]}`;
			        }
			    });
			
			params.token = md5(str);
			console.log('>>>>>',params)
			
			
			
	

            try {
     //            const response = await axiosInstance({
     //                method: 'post',
     //                // url: '/xsw/getConfig',
					// url: '/resHttp',
     //            });

     //            const [tun = {}] = response.data.syscontrol || []
     //            const server = tun.ice_server
     //            const iceServers = [
     //                {urls: server.stun_url},
     //                {
     //                    urls: server.turn_url,
     //                    username: server.username,
     //                    credential: server.password
     //                }
     //            ];
	 
	 uni.request({
	     url: 'http://112.124.57.249:9090/resHttp', // 你的API地址
	     method: 'POST',
	     data: params,
	     header: {
	         'content-type': 'application/x-www-form-urlencoded', // 默认值
	     },
	     success: (response) => {
	         console.log('success', response.data);
	 		const [tun = {}] = response.data.data.syscontrol || []
	 		        const server = tun.ice_server
	 		        const iceServers = [
	 		            {urls: server.stun_url},
	 		            {
	 		                urls: server.turn_url,
	 		                username: server.username,
	 		                credential: server.password
	 		            }
	 		        ];
	 				that.sdes(iceServers,params)
	 				
	 				
	 				
	     },
	     fail: (err) => {
	         console.log('failed', err);
	     }
	 });


                
            } catch (error) {
                console.error('Error during playback:', error);
            }
        },
		
		async sdes(iceServers,token){
			const pc = new RTCPeerConnection({
			            iceServers,
			            iceTransportPolicy: 'all',
			            bundlePolicy: 'balanced',
			            rtcpMuxPolicy: 'require',
			            iceCandidatePoolSize: 0
			        });
			
			        pc.oniceconnectionstatechange = function (event) {
			            console.log('ICE connection state changed to:', pc.iceConnectionState);
			        };
			
			        pc.onconnectionstatechange = function (event) {
			            console.log('Connection state changed to:', pc.connectionState);
			        };
			
			        pc.onsignalingstatechange = function (event) {
			            console.log('Signaling state changed to:', pc.signalingState);
			        };
			
			        pc.ontrack = (event) => {
			            const [remoteStream] = event.streams;
			            const remoteVideoElement = document.getElementById('remoteVideo');
			            remoteVideoElement.srcObject = remoteStream;
			        };
			
			        const offer = await pc.createOffer({
			            offerToReceiveVideo: 1,
			            offerToReceiveAudio: 1,
			            voiceActivityDetection: true,
			            iceRestart: false
			        });
			        // 设置本地描述
			        await pc.setLocalDescription(offer);
					console.log('localDescription>>>>>',pc.localDescription)
					
					
					
					var that = this
					const mySecret = "f6fdffe48c908deb0f4c3bd36c032e72"
					var params = {}
					params.t = (new Date().getTime() / 1000).toFixed(0)
					let str = "";
					    let keys = Object.keys(params);
					    keys.push("secret");
					    keys = keys.sort(); // 对参数 key 进行排序
					    keys.forEach((key) => {
					        if (key == "token") {
					            return;
					        }
					        if (str != "") {
					            str += "&";
					        }
					        if (key == "secret") {
					            str += `${key}=${mySecret}`;
					        } else {
					            str += `${key}=${params[key]}`;
					        }
					    });
					
					params.token = md5(str);
					console.log('>>>>>',params)
					
					
					
				    let datatoken = {
						't':params.t,
						'token':params.token,
						'streamPath':'hlsram/live0',
						'sdp':JSON.stringify(pc.localDescription.sdp),
						'type':"offer"
					}
					
					uni.request({
					    url: 'http://112.124.57.249:9090/resHttp2', // 你的API地址
					    method: 'POST',
						data: datatoken,
						header: {
						    'content-type': 'application/x-www-form-urlencoded', // 默认值
						},
					    success: (response) => {
					        console.log('success>>>', response);
							
									
									
					    },
					    fail: (err) => {
					        console.log('failed', err);
					    }
					});
					
					
		},
    },
	
}
</script>
<style scoped lang="scss">

</style>